from django.db import models
from django.conf import settings
from django.utils import timezone
from cloudinary.models import CloudinaryField

from activities.models import Activity
from users.models import User


class Follow(models.Model):
    """关注关系"""
    follower = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='following', verbose_name='关注者')
    following = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='followers', verbose_name='被关注者')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='关注时间')
    
    class Meta:
        db_table = 'follows'
        verbose_name = '关注'
        verbose_name_plural = '关注'
        unique_together = ['follower', 'following']
    
    def __str__(self):
        return f"{self.follower.username} -> {self.following.username}"


class Friendship(models.Model):
    """好友关系"""
    STATUS_CHOICES = (
        ('pending', '待确认'),
        ('accepted', '已接受'),
        ('rejected', '已拒绝'),
    )
    
    from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_friend_requests', verbose_name='发起者')
    to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='received_friend_requests', verbose_name='接收者')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='pending', verbose_name='状态')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'friendships'
        verbose_name = '好友关系'
        verbose_name_plural = '好友关系'
        unique_together = ['from_user', 'to_user']
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.from_user.username} -> {self.to_user.username} ({self.status})"
    
    @classmethod
    def are_friends(cls, user1, user2):
        """检查两个用户是否是好友"""
        return cls.objects.filter(
            models.Q(from_user=user1, to_user=user2, status='accepted') |
            models.Q(from_user=user2, to_user=user1, status='accepted')
        ).exists()
    
    @classmethod
    def get_friends(cls, user):
        """获取用户的所有好友"""
        from django.contrib.auth import get_user_model
        User = get_user_model()
        
        friend_ids = cls.objects.filter(
            models.Q(from_user=user, status='accepted') |
            models.Q(to_user=user, status='accepted')
        ).values_list('from_user_id', 'to_user_id')
        
        all_ids = set()
        for from_id, to_id in friend_ids:
            all_ids.add(from_id if from_id != user.id else to_id)
        
        return User.objects.filter(id__in=all_ids)


class Group(models.Model):
    """群组"""
    name = models.CharField(max_length=100, verbose_name='群组名称')
    description = models.TextField(blank=True, verbose_name='群组描述')
    # 群组头像 - 使用Cloudinary存储
    avatar = CloudinaryField(
        '群组头像',
        folder='group_avatars',
        blank=True,
        null=True,
        transformation={
            'width': 200,
            'height': 200,
            'crop': 'fill',
            'gravity': 'face'
        }
    )
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='created_groups', verbose_name='创建者')
    members = models.ManyToManyField(settings.AUTH_USER_MODEL, through='GroupMembership', related_name='joined_groups', verbose_name='成员')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'groups'
        verbose_name = '群组'
        verbose_name_plural = '群组'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.name
    
    def get_last_message(self):
        """获取最后一条消息"""
        return self.group_messages.last()


class GroupMembership(models.Model):
    """群组成员关系"""
    ROLE_CHOICES = (
        ('owner', '群主'),
        ('admin', '管理员'),
        ('member', '成员'),
    )
    
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='memberships', verbose_name='群组')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='group_memberships', verbose_name='用户')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='member', verbose_name='角色')
    joined_at = models.DateTimeField(auto_now_add=True, verbose_name='加入时间')
    
    class Meta:
        db_table = 'group_memberships'
        verbose_name = '群组成员'
        verbose_name_plural = '群组成员'
        unique_together = ['group', 'user']
        ordering = ['-joined_at']
    
    def __str__(self):
        return f"{self.user.username} in {self.group.name} ({self.role})"


class Conversation(models.Model):
    """会话（私聊）"""
    participants = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='conversations', verbose_name='参与者')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        db_table = 'conversations'
        verbose_name = '会话'
        verbose_name_plural = '会话'
        ordering = ['-updated_at']
    
    def __str__(self):
        return f"会话 {self.id}"
    
    def get_other_participant(self, user):
        """获取会话中的另一个参与者"""
        try:
            # 确保这个方法正确实现
            other_participants = self.participants.exclude(id=user.id)
            if other_participants.exists():
                return other_participants.first()
            return None
        except Exception as e:
            print(f"获取其他参与者错误: {str(e)}")
            return None
    
    def get_last_message(self):
        """获取最后一条消息"""
        return self.messages.last()


class Message(models.Model):
    """私信"""
    MESSAGE_TYPES = (
        ('text', '文本'),
        ('image', '图片'),
        ('file', '文件'),
    )
    
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages', verbose_name='会话', null=True, blank=True)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_messages', verbose_name='发送者')
    content = models.TextField(verbose_name='消息内容')
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, default='text', verbose_name='消息类型')
    is_read = models.BooleanField(default=False, verbose_name='是否已读')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')
    
    class Meta:
        db_table = 'messages'
        verbose_name = '私信'
        verbose_name_plural = '私信'
        ordering = ['created_at']
    
    def __str__(self):
        return f"{self.sender.username}: {self.content[:20]}..."
    
    def mark_as_read(self):
        """标记为已读"""
        self.is_read = True
        self.save(update_fields=['is_read'])


class GroupMessage(models.Model):
    """群组消息"""
    MESSAGE_TYPES = (
        ('text', '文本'),
        ('image', '图片'),
        ('file', '文件'),
        ('system', '系统消息'),
    )
    
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_messages', verbose_name='群组')
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sent_group_messages', verbose_name='发送者', null=True, blank=True)
    content = models.TextField(verbose_name='消息内容')
    message_type = models.CharField(max_length=10, choices=MESSAGE_TYPES, default='text', verbose_name='消息类型')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='发送时间')
    
    class Meta:
        db_table = 'group_messages'
        verbose_name = '群组消息'
        verbose_name_plural = '群组消息'
        ordering = ['created_at']
    
    def __str__(self):
        sender_name = self.sender.username if self.sender else '系统'
        return f"{sender_name} in {self.group.name}: {self.content[:20]}..."


class CommentLike(models.Model):
    """评论点赞"""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='用户')
    comment = models.ForeignKey('activities.ActivityComment', on_delete=models.CASCADE, related_name='likes', verbose_name='评论')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='点赞时间')
    
    class Meta:
        db_table = 'comment_likes'
        verbose_name = '评论点赞'
        verbose_name_plural = '评论点赞'
        unique_together = ['user', 'comment']
    
    def __str__(self):
        return f"{self.user.username} likes comment"



class SystemNotification(models.Model):
    NOTIFICATION_TYPES = (
        ('activity_rejected', '活动被拒绝'),
        ('activity_approved', '活动被通过'),
        ('system', '系统通知'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='接收用户')
    title = models.CharField(max_length=200, verbose_name='通知标题')
    content = models.TextField(verbose_name='通知内容')
    notification_type = models.CharField(max_length=50, choices=NOTIFICATION_TYPES, default='system')
    related_activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True, blank=True)
    admin_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='sent_notifications', verbose_name='操作管理员')
    is_read = models.BooleanField(default=False, verbose_name='已读')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '系统通知'
        verbose_name_plural = '系统通知'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.title} - {self.user.username}"